package com.sayimo.maker.commons.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.DES3;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.commons.utils.RedisUtils;

public class TokenInterceptor implements HandlerInterceptor{
	
	private static Log logger = LogFactory.getLog(TokenInterceptor.class);
	
	//存放不需要SAYIMO_TOKEN验证的借口链接
	List<String> excludeUrls = new ArrayList<String>(){
		{
			add("/goods/getindextemplate");
			add("/user/getallprovinces");
			add("/user/getcitiesbyprovincecode");
			add("/user/getareasbycitycode");
			add("/user/getaddressbyareacode");
			add("/goods/goodsclasslist");
			add("/goods/getgoodslistbyclassid");
			add("/goods/getgoodsinfo");
			add("/goods/getgoodscomments");
			add("/goods/searchgoodsbyname");
			add("/goods/getgoodscount");
			add("/goods/changegoodsnormsvalue");
			add("/goods/getallnormsvalues");
			add("/goods/getnormsinfo");
			add("/base/getallems");
			add("/goods/suggestgoodssearch");
			add("/base/getnewapp");
			add("/base/uploadfilebackid");
			add("/user/makerlogin");
			add("/user/registeraccount");
			add("/user/sendsms");
			add("/user/checksms");
			add("/goods/getbrandlistbyclassid");
			add("/base/uploadfilebackurl");
			add("/user/getallasjson");
			add("/user/getareabycodeasjson");
			add("/goods/unionshoplist");
			add("/goods/unionshopbyid");
			add("/goods/queryenterprisecomment");
			add("/goods/initsearchengine");
			add("/goods/insertsearchengine");
			add("/goods/deletesearchengine");
			add("/base/getadpositionlistbytag");
			add("/base/uploadfile");
			add("/user/getmembersmustread");
			add("/orders/callbackalipay");
			add("/user/updatepassword");
			add("/user/createqrcode");
			
		}
	};

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		 
		String servletPath = request.getServletPath();
		logger.info("servletPath = " + servletPath);
		if (excludeUrls.size() > 0) {
			for(String x:excludeUrls){
				if(servletPath.contains(x)){
					return true;
				}
			}
		}
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		// 验证token
		String token = request.getHeader("sayimotoken"); // token:customerId
		logger.info("token = " + token);
		if (token == null || token.equals("")) { // token空验证
			
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.TOKEN_IS_NULL);
			resultMap.put(Constant.MSG, "token为空");
			response.getWriter().write(JSONUtil.writeValueAsString(resultMap));
			
			return false;
		}
		
		byte[] bToken = Base64.decodeBase64(token.getBytes("UTF-8"));
		token = new String(bToken);
		if (token.split(":").length < 2) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.TOKEN_FORMAT_WRONG);
			resultMap.put(Constant.MSG, "token格式错误");
			
			response.getWriter().print(JSONUtil.writeValueAsString(resultMap));
			return false;
		}
		String customerId = token.split(":")[1];
		token = token.split(":")[0];
		
		
		if (!RedisUtils.hasKey(token)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.TOKEN_IS_INVALID);
			resultMap.put(Constant.MSG, "token无效");
			response.getWriter().print(JSONUtil.writeValueAsString(resultMap));
			
			return false;
		}
		
		// 获取用户信息
		String redisCustomerInfo = DES3.decode(RedisUtils.getStringValue(token));
		// time + "|"+customerList.get(0).getId()+"|"+customerList.get(0).getAccout()+"|" + time
		String[] redisInfos = redisCustomerInfo.split("\\|");
		Integer redisCustomerId = Integer.valueOf(redisInfos[1]);
		String redisCustomerAccount = String.valueOf(redisInfos[2]);
		logger.info("&&&&&&&&&&&&&&&&&& customerId+"+customerId);
		logger.info("&&&&&&&&&&&&&&&&&& redisCustomerId+"+redisCustomerId);
		if (Integer.parseInt(customerId) != redisCustomerId) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.TOKEN_IS_TAMPERED);
			resultMap.put(Constant.MSG, "token被篡改");
			
			response.getWriter().print(JSONUtil.writeValueAsString(resultMap));
			return false;
		}
		
		request.setAttribute("customerId", redisCustomerId);
		request.setAttribute("accout", redisCustomerAccount);
		
		return true;
	}
}
